package com.baijiaoxi.common.model.excel;

import com.baijiaoxi.common.model.UUID;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ExcelImportResultStorage {
    private Map<String, ExcelImportErrResult> store;

    public ExcelImportResultStorage() {
        this.store = new HashMap<>();
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    for (String key : store.keySet()) {
                        Long timestamp = store.get(key).timestamp;
                        if (System.currentTimeMillis() - timestamp >= 60 * 15 * 1000)
                            store.remove(key);
                    }
                } catch (Exception e) {
                    log.error("本次检查失效的导入结果失败", e);
                }
            }
        }, 10, 10, TimeUnit.MINUTES);
    }

    class ExcelImportErrResult {
        protected byte[] excel;

        private Long timestamp;

        public ExcelImportErrResult(byte[] excel) {
            this.excel = excel;
            this.timestamp = System.currentTimeMillis();//15分钟
        }
    }

    public String put(byte[] bytes) {
        String key = UUID.uuid();
        store.put(key, new ExcelImportErrResult(bytes));
        return key;
    }

    public byte[] getAndRemove(String uuid) {
        ExcelImportErrResult excelImportErrResult = store.get(uuid);
        store.remove(uuid);
        return excelImportErrResult.excel;
    }


}
